# 定义工具类
# 自定义过滤器
from flask import session, current_app, g

from info import constants
from info.models import User, News
import functools

def index_class(index):
    if index == 1:
        return 'first'
    elif index == 2:
        return 'second'
    elif index == 3:
        return 'third'
    return ""

# 定义装饰器
def user_login_data(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # 获取session中的用户id
        user_id = session.get('user_id', None)
        # 根据获取的用户id，在数据库中查询对应用户信息
        user = None
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception as a:
                current_app.logger.error(a)
        # 右侧新闻点击排行逻辑
        # news_list = []
        # try:
        #     news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
        # except Exception as a:
        #     current_app.logger.error(a)
        # # 按照查询取出的是news对象，进一步遍历对象，将对象的字典添加至字典列表中
        # news_dict_list = []
        # for news in news_list:
        #     news_dict_list.append(news.to_basic_dict())
        # g.news_dict_list = news_dict_list
        g.user = user
        return func(*args, **kwargs)
    return wrapper
